package dao;

import util.Condition;
import util.JdbcHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class CommonDao {
    private static CommonDao commonDao = new CommonDao();
    private CommonDao() {
    }
    public static CommonDao getInstance() {
        return commonDao;
    }
//    public int count(Connection conn, String tableName) throws SQLException {
//        String sql_count = "select count(*) from " + tableName;
//        PreparedStatement pstmt_count = conn.prepareStatement(sql_count);
//        int counter = 0;
//        ResultSet resultSet_count = pstmt_count.executeQuery();
//        if (resultSet_count.next()) {
//            counter = resultSet_count.getInt("cnt");
//        }
//        JdbcHelper.close(resultSet_count, pstmt_count, conn);
//        return counter;
//    }
    public int count(Connection conn, String tableName, List<Condition> conditionList) throws SQLException {
        StringBuilder sql_count =new StringBuilder("select count(id) as cnt from " + tableName);
        if (conditionList!= null) {
            StringBuilder whereClause = new StringBuilder(Condition.toWhereClause(conditionList));
            sql_count.append(whereClause);
        }
        PreparedStatement ps = conn.prepareStatement(sql_count.toString());
        int counter = 0;
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            counter = rs.getInt("cnt");
        }
        JdbcHelper.close(rs, ps);
        return counter;
    }
}
